package com.sesample.seandroidsample;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Currency;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.facebook.AppEventsLogger;

public class CartFragment extends Fragment {
  /*
   * Internal class for the customized list item view
   */
  private class CartAdapter extends ArrayAdapter<Cart.Item> {
    public CartAdapter(ArrayList<Cart.Item> items) {
      super(getActivity(), 0, items);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      /*
       * If we weren't given a view, inflate one
       */
      if (convertView == null) {
        convertView = getActivity().getLayoutInflater()
            .inflate(R.layout.list_item_cart, null);
      }

      Catalogue inventory = Catalogue.getInstance(getActivity());
      final Product p = inventory.getProductById(getItem(position).getProductId());

      TextView titleTextView =
          (TextView)convertView.findViewById(R.id.list_item_cart_product_name);
      titleTextView.setText(p.getName());
      TextView descriptionTextView =
          (TextView)convertView.findViewById(R.id.list_item_cart_number);
      descriptionTextView.setText("" + getItem(position).getNumber());

      final int pos = position;
      Button removeButton = (Button)convertView.findViewById(R.id.list_item_cart_remove);
      removeButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
          // TODO Auto-generated method stub
          remove(getItem(pos));
          notifyDataSetChanged();
          // Refresh the total price display
          updateTotalPrice();
        }
      });
      return convertView;
    }
  }

  private float mTotalPrice;
  private Cart mCart;
  private TextView mTotalPriceView;
  private CartAdapter mCartAdapter;

  public CartFragment() {
  }

  /**
   * Finish the checkout and clear the cart
   */
  private void checkout() {
    if (mCart.isEmpty()) {
      return;
    }

    AppEventsLogger logger = AppEventsLogger.newLogger(getActivity());
    // Log the purchase event
    logger.logPurchase(BigDecimal.valueOf(mTotalPrice), Currency.getInstance("USD"));

    // Popup about the event
    FragmentManager fm = getActivity().getSupportFragmentManager();
    String message = "logPurchase" + "\n" +
        "purchaseAmount: " + mTotalPrice + "\n" +
        "currency: USD";
    EventDialogFragment eventDialog = EventDialogFragment.newInstance(message);
    eventDialog.show(fm, "EventDialogFragment");

    // Clear the cart after purchase
    mCart.clearCart();
    mCartAdapter.addAll(mCart.getItems());
    mCartAdapter.notifyDataSetChanged();

    // Update the bottom display
    updateTotalPrice();
  }

  @TargetApi(11)
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mCart = Cart.getInstance(getActivity());

    setHasOptionsMenu(true);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
      if (null != NavUtils.getParentActivityName(getActivity())) {
        getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
      }
    }
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_cart, container, false);

    // The ListView for the cart items
    mCartAdapter = new CartAdapter(mCart.getItems());
    ListView cartView = (ListView)rootView.findViewById(R.id.list_cart);
    cartView.setAdapter(mCartAdapter);

    mTotalPriceView = (TextView)rootView.findViewById(R.id.cart_total_price);

    updateTotalPrice();

    // Checkout button
    Button checkoutButton = (Button)rootView.findViewById(R.id.button_check_out);
    checkoutButton.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        // TODO Auto-generated method stub
        checkout();
      }
    });

    return rootView;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
      if (null != NavUtils.getParentActivityName(getActivity())) {
        NavUtils.navigateUpFromSameTask(getActivity());
      }
      return true;
    default:
      return super.onOptionsItemSelected(item);
    }
  }

  /**
   * Called when the cart's content is changed to update the total price display
   */
  private void updateTotalPrice() {
    if (null == mCart) {
      mTotalPrice = 0;
    } else {
      mTotalPrice = mCart.calcTotalPrice();
    }

    mTotalPriceView.setText("" + mTotalPrice);
  }
}
